from flask import render_template, request, url_for, redirect, flash
from flask_login import login_user, login_required, logout_user, current_user

from helloflask import app, db
from helloflask.models import User, Movie


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if not current_user.is_authenticated:
            return redirect(url_for('index'))

        title = request.form.get('title')
        year = request.form.get('year')

        if not title or not year or len(year) > 4 or len(title) > 60:
            flash('invalid input.')
            return redirect(url_for('index'))
        movie = Movie(title=title, year=year)
        db.session.add(movie)
        db.session.commit()
        flash('Item Created')
        return redirect(url_for('index'))

    else:
        user = User.query.first()
        movies = Movie.query.all()
        return render_template('index.html', movies=movies)


@app.route('/hello')
def hello():
    return u'<h1>Hello Totoro!</h1><img src="http://helloflask.com/totoro.gif">'


@app.route('/greet', defaults={'name': 'baby'})
@app.route('/greet/<name>')
def greet(name):
    return 'hello, %s' % name


@app.route('/test')
def test_url_for():
    print(url_for('index'))
    print(url_for('greet', name='greyli'))
    return "test"


@app.route('/test/<int:number>')
def test_nunmber(number):
    return "test number is:" + str(number)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if not username or not password:
            flash('Invalid Input')
            return redirect(url_for('login'))
        user = User.query.first()
        if username == user.username and user.validate_password(password):
            login_user(user)
            flash('login success')
            return redirect(url_for('index'))

        flash('invalid username or password')
        return redirect(url_for('login'))
    return render_template('login.html')


@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('GoodBye')
    return redirect(url_for('index'))


@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    if request.method == 'POST':
        name = request.form['name']
        if not name or len(name) > 20:
            flash('Invalid input.')
            return redirect(url_for('settings'))
        current_user.name = name
        db.session.commit()
        flash('settings updated')
        return redirect(url_for('index'))

    return render_template('settings.html')


@app.route('/movie/edit/<int:movie_id>', methods=['GET', 'POST'])
@login_required
def edit(movie_id):
    movie = Movie.query.get_or_404(movie_id)
    if request.method == 'POST':
        title = request.form['title']
        year = request.form['year']
        if not title or not year or len(year) > 4 or len(title) > 60:
            flash('Invalid Input')
            return redirect(url_for('edit'), movie_id=movie_id)
        movie.title = title
        movie.year = year
        db.session.commit()
        flash('Item Updated')
        return redirect(url_for('index'))
    else:
        return render_template('edit.html', movie=movie)


@app.route('/movie/delete/<int:movie_id>', methods=['POST'])
def delete(movie_id):
    movie = Movie.query.get_or_404(movie_id)
    db.session.delete(movie)
    db.session.commit()
    flash("Item deleted!")
    return redirect(url_for('index'))
